package com.cn.zpark;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @PackageName: com.cn.zpark
 * @ClassName: ServletContextDemo04
 * @Description:
 * @author: RZS
 * @date: 2022/4/8  11:25
 */
@WebServlet("/scd4.do")
public class ServletContextDemo04 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取context对象
        ServletContext context = request.getServletContext();
        // 通过Context对象获取绑定数据
        Object count = context.getAttribute("count");
        // 将对象类型转为integer类型
        Integer number = (Integer) count;
        // +1
        ++ number;
        // 将修改之后的数据绑定到context对象中
        context.setAttribute("count", number);
        // 将信息响应到浏览器
        response.setContentType("text/html;charset=utf-8"); // 设置响应格式
        // 获取写出对象流
        PrintWriter writer = response.getWriter();
        writer.println("<h1>该网站被浏览的次数为： " + number + "次</h1>");
        writer.close();
    }
}
